package org.wheel.plugins.toolkit.sql.segment;

import lombok.Getter;
import org.wheel.plugins.toolkit.sql.core.SqlSegment;

import java.util.List;

@Getter
public class WithSegment implements SqlSegment {
    private final String cteName;      // 公用表表达式名字
    private final SqlSegment query;    // 里面可以是任意 SELECT/INSERT/UPDATE/DELETE
    private final List<String> columns; // 可选列列表

    private WithSegment(String cteName, SqlSegment query, List<String> columns) {
        this.cteName = cteName;
        this.query = query;
        this.columns = columns;
    }
    public static WithSegment as(String cteName, SqlSegment query, String... columns) {
        return new WithSegment(cteName, query, columns.length == 0 ? List.of() : List.of(columns));
    }
    @Override
    public String getSql() {
        String colPart = columns.isEmpty() ? "" : "(" + String.join(",", columns) + ")";
        return cteName + colPart + " AS (" + query.getSql() + ")";
    }
}
